package cc.wangzijie.ddns.aliyun.client;


import cc.wangzijie.ddns.aliyun.client.utils.AliyunDnsUtil;
import cc.wangzijie.ddns.aliyun.client.utils.NetworkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author wangzijie
 */
@Slf4j
@Component
public class DdnsTask implements Runnable {

    private static final String DOMAIN_NAME = "wangzijie.store";
    private final String domainName;
    private String oldPublicIpAddress;

    public DdnsTask() {
        this(DOMAIN_NAME);
    }

    public DdnsTask(String domainName) {
        this.domainName = domainName;
    }

    @Override
    public void run() {
        try {
            // 定时任务业务逻辑
            String publicIpAddress = NetworkUtil.getPublicIpAddress();
            if ("".equals(publicIpAddress)) {
                log.error("获取公网IP失败...");
            } else {
                if ( this.oldPublicIpAddress == null) {
                    // 初始化
                    log.info("初始化公网IP【 '{}' 】\n\n", publicIpAddress);
                    this.oldPublicIpAddress = publicIpAddress;
                    log.info("更新阿里云DNS解析设置");
                    AliyunDnsUtil.updateDdns( this.domainName, publicIpAddress );
                } else if ( !Objects.equals( this.oldPublicIpAddress, publicIpAddress) ) {
                    // 公网IP发生变动, 更新阿里云DNS解析设置
                    log.info("公网IP发生变动, 旧公网IP【 '{}' 】  ==>  新公网IP【 '{}' 】", oldPublicIpAddress, publicIpAddress);
                    this.oldPublicIpAddress = publicIpAddress;
                    log.info("更新阿里云DNS解析设置");
                    AliyunDnsUtil.updateDdns( this.domainName, publicIpAddress );
                } else {
                    log.info("公网IP未发生变动, 当前公网IP【 '{}' 】\n\n", publicIpAddress);
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}
